package com.ruoyi.wx.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
public class WeChatQrCodeUtil {

    private static final String QR_CODE_API = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";

    public static String generateTempQrCodeUrl(String userId) throws Exception {
        String expertAccessToken = WeChatTokenManager.getExpertAccessToken();
        String url = String.format(QR_CODE_API, expertAccessToken);

        String body = "{\n" +
                "  \"expire_seconds\": 604800,\n" +
                "  \"action_name\": \"QR_STR_SCENE\",\n" +
                "  \"action_info\": {\n" +
                "    \"scene\": {\n" +
                "      \"scene_str\": \"" + userId + "\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.getOutputStream().write(body.getBytes(StandardCharsets.UTF_8));

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) sb.append(line);
        reader.close();

        String jsonResult = sb.toString();

        // 解析ticket
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        String ticket = jsonObject.getString("ticket");

        // 拼接二维码地址（注意要对ticket做URL编码）
        String qrCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket, "UTF-8");

        return qrCodeUrl;
    }

    public static String generateTempQrCodeUrlUser(String userId) throws Exception {
        String expertAccessToken = WeChatTokenManager.getUserAccessToken();
        String url = String.format(QR_CODE_API, expertAccessToken);

        String body = "{\n" +
                "  \"expire_seconds\": 604800,\n" +
                "  \"action_name\": \"QR_STR_SCENE\",\n" +
                "  \"action_info\": {\n" +
                "    \"scene\": {\n" +
                "      \"scene_str\": \"" + userId + "\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.getOutputStream().write(body.getBytes(StandardCharsets.UTF_8));

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) sb.append(line);
        reader.close();

        String jsonResult = sb.toString();

        // 解析ticket
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        String ticket = jsonObject.getString("ticket");

        // 拼接二维码地址（注意要对ticket做URL编码）
        String qrCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket, "UTF-8");

        return qrCodeUrl;
    }

}
